﻿using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using WPFDataEditors.Classes;
using System.Windows.Documents;

namespace WPFDataEditors.RichTextBox.Control
{
    public class RichTextBox : System.Windows.Controls.Control
    {
        private static readonly Uri ControlThemeuri = new Uri("/WPFDataEditors;component/RichTextBox/Themes/Generic.xaml", UriKind.Relative);
        private readonly ResourceDictionary _controlThemeStyle = new ResourceDictionary { Source = ControlThemeuri };
        private void AddResouces()
        {

            if (!UriParser.IsKnownScheme("pack"))
                UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), "pack", -1);


            //Datagrid
            if (!Resources.MergedDictionaries.Contains(_controlThemeStyle))
                Resources.MergedDictionaries.Add(_controlThemeStyle);
        }

        public RichTextBox()
        {
            Loaded += RichTextBoxLoaded;
            AddResouces();
           
        }

        private ComboBox FontComboFast { get; set; }
        private ComboBox FontSizeCombo { get; set; }
        public System.Windows.Controls.RichTextBox TextArea { get;private set; }
        private ToggleButton BoldButton { get; set; }
        private ToggleButton UnderlineButton { get; set; }
        private ToggleButton ItalicButton { get; set; }
        private ToggleButton AlignRightButton { get; set; }
        private ToggleButton AlignLeftButton { get; set; }
        private ToggleButton AlignCenterButton { get; set; }
       

        void RichTextBoxLoaded(object sender, RoutedEventArgs e)
        {
            var fontComboFast = FindControls.FindChild<ComboBox>(this, "fontComboFast");
            if (fontComboFast != null)
            {
                FontComboFast = fontComboFast;
                fontComboFast.SelectionChanged += FontComboFastSelectionChanged;
            }
            var fontSizeCombo = FindControls.FindChild<ComboBox>(this, "fontSizeCombo");
            if(fontSizeCombo!=null)
            {
                FontSizeCombo = fontSizeCombo;
                fontSizeCombo.Items.Add("10");
                fontSizeCombo.Items.Add("12");
                fontSizeCombo.Items.Add("14");
                fontSizeCombo.Items.Add("18");
                fontSizeCombo.Items.Add("24");
                fontSizeCombo.Items.Add("36");
                fontSizeCombo.SelectionChanged += FontSizeComboSelectionChanged;
            }
            var textArea = FindControls.FindChild<System.Windows.Controls.RichTextBox>(this, "txtArea");
            if(textArea!=null)
            {
                TextArea = textArea;
                textArea.SelectionChanged += TextAreaSelectionChanged;
            }
            BoldButton = FindControls.FindChild<ToggleButton>(this, "ToolStripButtonBold");
            UnderlineButton = FindControls.FindChild<ToggleButton>(this, "ToolStripButtonUnderline");
            ItalicButton = FindControls.FindChild<ToggleButton>(this, "ToolStripButtonItalic");
            AlignRightButton = FindControls.FindChild<ToggleButton>(this, "ToolStripButtonAlignRight");
            AlignLeftButton = FindControls.FindChild<ToggleButton>(this, "ToolStripButtonAlignLeft");
            AlignCenterButton = FindControls.FindChild<ToggleButton>(this, "ToolStripButtonAlignCenter");
         }


        void TextAreaSelectionChanged(object sender, RoutedEventArgs e)
        {
            SetToolBar();
        }

      private void SetToolBar()
        {
            // Set font family combo
            var textRange = new TextRange(TextArea.Selection.Start, TextArea.Selection.End);
            var fontFamily = textRange.GetPropertyValue(TextElement.FontFamilyProperty);
            FontComboFast.SelectedItem = fontFamily;

            // Set font size combo
            var fontSize = textRange.GetPropertyValue(TextElement.FontSizeProperty);
            FontSizeCombo.Text = fontSize.ToString();

            // Set Font buttons
            if (!String.IsNullOrEmpty(textRange.Text))
            {
                BoldButton.IsChecked = textRange.GetPropertyValue(TextElement.FontWeightProperty).Equals(FontWeights.Bold);
                ItalicButton.IsChecked = textRange.GetPropertyValue(TextElement.FontStyleProperty).Equals(FontStyles.Italic);
                UnderlineButton.IsChecked = textRange.GetPropertyValue(Inline.TextDecorationsProperty).Equals(TextDecorations.Underline);
            }

            // Set Alignment buttons
            AlignLeftButton.IsChecked = textRange.GetPropertyValue(FlowDocument.TextAlignmentProperty).Equals(TextAlignment.Left);
            AlignCenterButton.IsChecked = textRange.GetPropertyValue(FlowDocument.TextAlignmentProperty).Equals(TextAlignment.Center);
            AlignRightButton.IsChecked = textRange.GetPropertyValue(FlowDocument.TextAlignmentProperty).Equals(TextAlignment.Right);
        }

        void FontSizeComboSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var fontSizeCombo = sender as ComboBox;
            if (fontSizeCombo==null)
                return;
            var textArea = FindControls.FindChild<System.Windows.Controls.RichTextBox>(this, "txtArea");
            if (textArea == null) return;
            // Exit if no selection
            if (fontSizeCombo.SelectedItem == null) return;

            // clear selection if value unset
            if (fontSizeCombo.SelectedItem.ToString() == "{DependencyProperty.UnsetValue}")
            {
                fontSizeCombo.SelectedItem = null;
                return;
            }

            // Process selection
            var pointSize = fontSizeCombo.SelectedItem.ToString();
            var pixelSize = Convert.ToDouble(pointSize) * (96 / 72);
            var textRange = new TextRange(textArea.Selection.Start, textArea.Selection.End);
            textRange.ApplyPropertyValue(TextElement.FontSizeProperty, pixelSize);
        }

        void FontComboFastSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var fontCombo = sender as ComboBox;
            if (fontCombo==null || fontCombo.SelectedItem == null) return;
            var textArea = FindControls.FindChild<System.Windows.Controls.RichTextBox>(this, "txtArea");
            if(textArea==null)return;
            var fontFamily = fontCombo.SelectedItem.ToString();
            var textRange = new TextRange(textArea.Selection.Start, textArea.Selection.End);
            textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, fontFamily);
        }

       

        protected void NotifyPropertyChanged<T, TP>(T source, Expression<Func<T, TP>> pe)
        {
            PropertyChanged.Raise(source, pe);
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}
